package hivi.vn.hivigold.activities;

import hivi.vn.hivigold.R;
import hivi.vn.hivigold.adapters.VoucherAdapter;
import hivi.vn.hivigold.database.Preferences;
import hivi.vn.hivigold.database.WebService;
import hivi.vn.hivigold.objects.Employee;
import hivi.vn.hivigold.objects.Item;
import hivi.vn.hivigold.objects.Partner;
import hivi.vn.hivigold.objects.Stock;
import hivi.vn.hivigold.objects.VoucherDetail;
import hivi.vn.hivigold.objects.VoucherMaster;
import hivi.vn.hivigold.utils.AccessDenied;
import hivi.vn.hivigold.utils.Formats;

import java.util.ArrayList;
import java.util.Date;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

public class VoucherActivity extends Activity {
	static final int ACTION_NEW = 1;
	static final int ACTION_VIEW = 3;
	static final int ACTION_START = 2;
	public static final String ITEM_SELECTED = "ITEM_SELECTED";
	int CURRENT_ACTION = 2;
	int ACTION_EDIT_ITEM = 1;
	int ACTION_NEW_ITEM = 2;

	static final int SCAN_REQUEST = 4;
	public static final int ITEM_REQUEST = 5;
	ImageButton imgKhach_hang;
	EditText txtSo_ct;
	EditText txtNgay_ct;
	EditText txtEmployee;
	EditText txtStock;
	EditText txtNote;
	EditText txtBarcode;
//	LinearLayout lnlFooter;
	EditText txtMoney;
	EditText txtCk;
	EditText txtTotal;
	TextView tvPartnerName;
	ImageButton btnNew;
	// Button btnPrint;
	ImageButton btnSavePrint;
	// Button btnDelete;
	// Button btnSearch;
	ImageButton btnMore;
	ImageButton btnEnter;
	ImageButton btnScan;
	ImageButton btnSave;
	ImageButton btnCancelV;
	ListView lstVoucher;

	TextView txtNameItem;
	EditText txtTlg_da;
	EditText txtTlg_au;
	EditText txtHlg_au;
	EditText txtTien_da;
	EditText txtTien_cong;
	EditText txtTong_tlg;
	EditText txtGia_au;
	EditText txtGia_ban11;
	EditText txtSo_luong;
	EditText txtThanh_tien;

	RadioButton rboMua;
	RadioButton rboBan;
	Button btnAdd;
	Button btnCancel;
	Button btnCal;

	Date ngay_ct;
	ProgressDialog progressDialog;
	AlertDialog itemDialog;
	ArrayList<VoucherDetail> arrVoucherDetail;
	ArrayList<Item> arrItem;
	VoucherAdapter adapter;
	VoucherMaster master;
	int flagChangeValue = -1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		setContentView(R.layout.voucher_layout);
		imgKhach_hang = (ImageButton) findViewById(R.id.imgPartner);
		txtSo_ct = (EditText) findViewById(R.id.txtSo_ct);
		txtNgay_ct = (EditText) findViewById(R.id.txtNgay_ct);
		txtEmployee = (EditText) findViewById(R.id.txtEmployee);
		txtStock = (EditText) findViewById(R.id.txtStock);
		txtNote = (EditText) findViewById(R.id.txtNote);
		txtBarcode = (EditText) findViewById(R.id.txtBarcode);

		tvPartnerName = (TextView) findViewById(R.id.tvPartnerName);
		btnNew = (ImageButton) findViewById(R.id.btnNew);
		// btnPrint = (Button) findViewById(R.id.btnPrint);
		btnSavePrint = (ImageButton) findViewById(R.id.btnSaveAndPrint);
		// btnDelete = (Button) findViewById(R.id.btnDelete);
		// btnSearch = (Button) findViewById(R.id.btnSearch);
		btnEnter = (ImageButton) findViewById(R.id.btnEnter);
		btnScan = (ImageButton) findViewById(R.id.btnScan);
		btnSave = (ImageButton) findViewById(R.id.btnSave);
		btnCancelV = (ImageButton) findViewById(R.id.btnCancel);
		btnMore = (ImageButton) findViewById(R.id.btnMore);
		lstVoucher = (ListView) findViewById(R.id.lstVoucher);
		txtMoney = (EditText) findViewById(R.id.txtTien_hang);
		txtCk = (EditText) findViewById(R.id.txtCk);
		txtTotal = (EditText) findViewById(R.id.txtTotal);
		lstVoucher.setOnItemClickListener(onItemClickListener);
		lstVoucher.setOnItemLongClickListener(onItemLongClickListener);
		btnNew.setOnClickListener(onClick);
		btnSave.setOnClickListener(onClick);
		btnSavePrint.setOnClickListener(onClick);
		// btnPrint.setOnClickListener(onClick);
		// btnDelete.setOnClickListener(onClick);
		// btnSearch.setOnClickListener(onClick);
		btnEnter.setOnClickListener(onClick);
		btnScan.setOnClickListener(onClick);
		btnCancelV.setOnClickListener(onClick);
		btnMore.setOnClickListener(onClick);
		imgKhach_hang.setOnClickListener(onClick);

		txtEmployee.setOnLongClickListener(onLong);
		txtStock.setOnLongClickListener(onLong);
		txtNgay_ct.setOnClickListener(onClick);
		txtCk.setOnEditorActionListener(new TextView.OnEditorActionListener() {
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_NEXT) {
					callist();
				}
				return false;
			}
		});
		txtCk.setOnKeyListener(new View.OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				// TODO Auto-generated method stub
				if(keyCode == KeyEvent.KEYCODE_ENTER)
				{
					callist();
				}
				return false;
			}
		});
		
		setAction();
		setValue();
		/*
		 * Bundle bundle = getIntent().getExtras(); if (bundle != null) { Item i
		 * = (Item) bundle.getSerializable(ITEM_SELECTED); if (i != null) {
		 * CURRENT_ACTION = ACTION_NEW; setAction(); setValue();
		 * txtBarcode.setText(i.getVtID()); showDetailItem(); } } else {
		 * 
		 * }
		 */
	}

	OnItemClickListener onItemClickListener = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			// TODO Auto-generated method stub
			if (CURRENT_ACTION == ACTION_NEW) {
				final int position = arg2;
				Item i = arrItem.get(position);
				VoucherDetail v = arrVoucherDetail.get(position);
				ItemActivity.onStartIntent(VoucherActivity.this, i, v.getSo_luong(), v.getTien(), v.getCtID1().equals("BANHANG") ? "GIABAN" : "GIAMUA", ACTION_EDIT_ITEM, position);
			}

		}

	};

	OnItemLongClickListener onItemLongClickListener = new OnItemLongClickListener() {
		@Override
		public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
				int arg2, long arg3) {
			// TODO Auto-generated method stub
			if (CURRENT_ACTION == ACTION_NEW) {
				final int position = arg2;
				AlertDialog.Builder builder = new AlertDialog.Builder(
						getBaseContext());
				builder.setMessage(R.string.confirm_ask);
				builder.setTitle(R.string.confirm);

				builder.setNegativeButton(R.string.btn_ok,
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								arrItem.remove(position);
								arrVoucherDetail.remove(position);
								adapter.swapData(arrVoucherDetail);
								callist();
								dialog.dismiss();
							}
						});
				builder.setPositiveButton(R.string.btn_cancel,
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								dialog.dismiss();
							}
						});

				AlertDialog alert = builder.create();
				alert.show();
			}
			return true;
		}
	};

	OnLongClickListener onLong = new OnLongClickListener() {

		@Override
		public boolean onLongClick(View v) {
			// TODO Auto-generated method stub
			if (v.getId() == R.id.txtEmployee) {
				Intent i = new Intent(getBaseContext(), SelectEmployee.class);
				startActivityForResult(i, SelectEmployee.SELECTED_EMPLOYEE_KEY);
			} else if (v.getId() == R.id.txtStock) {
				Intent i = new Intent(getBaseContext(), SelectStock.class);
				startActivityForResult(i, SelectStock.SELECTED_STOCK_KEY);
			}
			return true;
		}
	};

	OnClickListener onClick = new OnClickListener() {
		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			switch (arg0.getId()) {
			case R.id.btnNew:
				if (!AccessDenied.HD00) {
					Toast.makeText(getBaseContext(), R.string.warning_access_denied,
							Toast.LENGTH_LONG).show();
					return;
				}
				CURRENT_ACTION = ACTION_NEW;
				setAction();
				setValue();
				break;
			case R.id.btnScan:
				Intent i = new Intent("com.google.zxing.client.android.SCAN");
				i.putExtra("SCAN_MODE", "CODE_128");
				startActivityForResult(i, SCAN_REQUEST);
				break;
			case R.id.btnSave:
				onSave(false, 1);
				break;
			case R.id.btnSaveAndPrint:
				if (!AccessDenied.HD07) {
					Toast.makeText(getBaseContext(), R.string.warning_access_denied,
							Toast.LENGTH_LONG).show();
					return;
				}
				onSave(true, 1);
				break;
			case R.id.btnMore:
				onMore();
				break;
			case R.id.btnEnter:
				hideKeyboard();
				showDetailItem();
				break;
			case R.id.imgPartner:
				Intent i1 = new Intent(getBaseContext(), SelectPartner.class);
				startActivityForResult(i1, SelectPartner.SELECTED_PARTNER_KEY);
				break;
			case R.id.btnCancel:
				CURRENT_ACTION = ACTION_START;
				setAction();
				setValue();
				break;
			case R.id.txtNgay_ct:
				DatePickerDialog mDatePickerDialog = new DatePickerDialog(
						getBaseContext(), mDateSetListener,
						Formats.getComDateNow(ngay_ct, "yyyy"),
						(Formats.getComDateNow(ngay_ct, "MM") - 1),
						Formats.getComDateNow(ngay_ct, "dd"));
				mDatePickerDialog.setTitle(R.string.ngay_ct);
				mDatePickerDialog.show();
				break;
			default:
				break;
			}
		}
	};

	private void onDelete() {
		if (!AccessDenied.HD02) {
			Toast.makeText(getBaseContext(), R.string.warning_access_denied,
					Toast.LENGTH_LONG).show();
			return;
		}
		
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(R.string.confirm_ask);
		builder.setTitle(R.string.confirm);

		builder.setNegativeButton(R.string.btn_ok,
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						DeleteVoucherAsync delete = new DeleteVoucherAsync();
						delete.execute(master.getStt_rec(), master.getSo_ct());
					}
				});
		builder.setPositiveButton(R.string.btn_cancel,
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.dismiss();
					}
				});

		AlertDialog alert = builder.create();
		alert.show();
	}

	private void onSave(boolean print, int step) {
		boolean flagDenied = false;
		if(step == 1)
		{
			flagDenied = AccessDenied.HD07;
		}else
		{
			flagDenied = AccessDenied.HD08;
		}
		if (!flagDenied) {
			Toast.makeText(getBaseContext(), R.string.warning_access_denied,
					Toast.LENGTH_LONG).show();
			return;
		}
		
		if (checkValid()) {
			VoucherAsync save = new VoucherAsync(print, step);
			save.execute();
		} else {
			Toast.makeText(getBaseContext(), R.string.warning_notempty,
					Toast.LENGTH_LONG).show();
		}
	}

	void showKeyboard() {
		InputMethodManager imm = (InputMethodManager) getBaseContext()
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		if (imm != null)
			imm.showSoftInput(txtBarcode, 0);
	}

	void hideKeyboard() {
		InputMethodManager imm = (InputMethodManager) getBaseContext()
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		if (imm != null)
			imm.hideSoftInputFromWindow(txtBarcode.getWindowToken(), 0);
	}

	private void onMore() {
		AlertDialog.Builder more = new AlertDialog.Builder(VoucherActivity.this);
		more.setTitle(R.string.choose);
		final int array = CURRENT_ACTION == ACTION_START ? R.array.voucher_more_menu_start
				: CURRENT_ACTION == ACTION_VIEW ? R.array.voucher_more_menu_view
						: R.array.voucher_more_menu_new;
		more.setItems(getResources().getStringArray(array),
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						switch (array) {
						case R.array.voucher_more_menu_new:
							switch (which) {
							case 0:
								onSave(false, 0);
								break;
							case 1:
								onSave(true, 0);
								break;
							}
							break;
						case R.array.voucher_more_menu_start:
							if (!AccessDenied.HD04) {
								Toast.makeText(getBaseContext(), R.string.warning_access_denied,
										Toast.LENGTH_LONG).show();
								return;
							}
							VoucherHistory.onStartIntent(getBaseContext());
							break;
						case R.array.voucher_more_menu_view:
							switch (which) {
							case 0:
								startPrint(master.getStt_rec());
								break;
							case 1:
								onDelete();
								break;
							case 2:
								VoucherHistory.onStartIntent(getBaseContext());
								break;
							}
							break;
						}
						dialog.dismiss();
					}
				});
		more.create().show();
	}

	private void startPrint(final String stt_rec) {
		if (!AccessDenied.HD03) {
			Toast.makeText(getBaseContext(), R.string.warning_access_denied,
					Toast.LENGTH_LONG).show();
			return;
		}
		
		AlertDialog.Builder builder = new AlertDialog.Builder(
				VoucherActivity.this);
		builder.setItems(R.array.printtype, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub
				arg0.dismiss();
				PrintVoucherAsync async = new PrintVoucherAsync(arg1+1);
				async.execute(stt_rec);
			}
		});
		final AlertDialog alert = builder.create();
		alert.show();
	}

	private boolean checkValid() {
		if (master.getFK_doitacID() == null) {
			return false;
		}
		if (master.getFK_bpkdID() == null) {
			return false;
		}
		if (master.getFK_khoID() == null) {
			return false;
		}
		if (arrVoucherDetail.size() == 0) {
			return false;
		}

		callist();

		master.setTien_hang(txtMoney.getText().toString().trim().equals("") ? 0
				: Double.valueOf(txtMoney.getText().toString().trim()
						.replace(",", "")));
		master.setT_Sl(txtMoney.getTag() == null ? 0 : Double.valueOf(txtMoney
				.getTag().toString().trim().replace(",", "")));
		master.setTien_ck(txtCk.getText().toString().trim().equals("") ? 0
				: Double.valueOf(txtCk.getText().toString().trim()
						.replace(",", "")));
		master.setT_Tien(txtTotal.getText().toString().trim().equals("") ? 0
				: Double.valueOf(txtTotal.getText().toString().trim()
						.replace(",", "")));
		master.setT_Sl(txtMoney.getTag() == null ? 0 : Double.valueOf(txtMoney
				.getTag().toString().replace(",", "")));
		master.setUser_id0(Preferences.getPreferenceValue(getBaseContext(),
				Preferences.USERID));
		master.setUser_id2(Preferences.getPreferenceValue(getBaseContext(),
				Preferences.USERID));
		master.setNgay_ct(Formats.DateFormatInsert(ngay_ct));
		master.setDien_Giai(txtNote.getText().toString());

		return true;
	}

	DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			// TODO Auto-generated method stub
			ngay_ct = Formats.createDate(year, monthOfYear, dayOfMonth);
			txtNgay_ct.setText(Formats.DateFormatDisplay(ngay_ct));
		}
	};

	private void showDetailItem() {
		if (txtBarcode.getText().length() != 0) {
			//btnEnter.setFocusable(true);
			final String barcode = txtBarcode.getText().toString().trim();
			txtBarcode.setText("");
			AlertDialog.Builder builder = new AlertDialog.Builder(
					VoucherActivity.this);
			final AlertDialog alert;
			builder.setItems(R.array.buysale, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					// TODO Auto-generated method stub
					if(arg1 == 0)
					{
						ItemAsync itemAsync = new ItemAsync(barcode, "GIABAN");
						itemAsync.execute();
					}else
					{
						ItemAsync itemAsync = new ItemAsync(barcode, "GIAMUA");
						itemAsync.execute();
					}
					arg0.dismiss();
				}
			});
			alert = builder.create();
			alert.show();
		}
	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			Bundle bundle = data.getExtras();
			switch (requestCode) {
			case SelectPartner.SELECTED_PARTNER_KEY:
				Partner p = (Partner) bundle
						.getSerializable(SelectPartner.SELECTED_PARTNER);
				tvPartnerName.setText(p.getPartnerID() + "-"
						+ p.getPartnerName());
				Bitmap bm = Formats.creatBitmap(getBaseContext(),
						p.getPartnerImage());
				if (bm == null) {
					imgKhach_hang.setImageResource(R.drawable.partnera);
				} else {
					imgKhach_hang.setImageBitmap(bm);
				}
				imgKhach_hang.setTag(p);
				master.setFK_doitacID(p.getPartnerID());
				break;
			case SelectEmployee.SELECTED_EMPLOYEE_KEY:
				Employee e = (Employee) bundle
						.getSerializable(SelectEmployee.SELECTED_EMPLOYEE);
				txtEmployee.setText(e.getEmployeeName());
				txtEmployee.setTag(e);
				master.setFK_bpkdID(e.getEmployeeID());
				break;
			case SelectStock.SELECTED_STOCK_KEY:
				Stock s = (Stock) bundle
						.getSerializable(SelectStock.SELECTED_STOCK);
				txtStock.setText(s.getStockName());
				txtStock.setTag(s);
				master.setFK_khoID(s.getStockID());
				break;
			case SCAN_REQUEST:
				txtBarcode.setText(data.getStringExtra("SCAN_RESULT"));
				showDetailItem();
				break;
			case ITEM_REQUEST:
				if(CURRENT_ACTION != ACTION_NEW)
				{
					CURRENT_ACTION = ACTION_NEW;
					setAction();
					setValue();
				}
				int action = bundle.getInt(ItemActivity.ACTION_KEY);
				int position = bundle.getInt(ItemActivity.POSITION_KEY);
				String buysale = bundle.getString(ItemActivity.SALEBUY_KEY);
				Double number = bundle.getDouble(ItemActivity.NUMBER_KEY);
				Double money = bundle.getDouble(ItemActivity.MONEY_KEY);
				Item i = (Item) bundle.getSerializable(ItemActivity.ITEM_KEY);
				Log.i("action_view", action +" onActivityResul");
				if(action==ACTION_NEW_ITEM)
				{
					addItem(i, buysale, number, money);
				}else
				{
					editItem(i, buysale, number, money, position);
				}
				break;
			}
		}
	};

	private void setAction() {
		switch (CURRENT_ACTION) {
		case ACTION_NEW:
			imgKhach_hang.setEnabled(true);
			txtEmployee.setEnabled(true);
			txtStock.setEnabled(true);
			txtNote.setEnabled(true);
			txtNgay_ct.setEnabled(true);
			/*txtBarcode.setEnabled(true);
			btnScan.setEnabled(true);
			btnEnter.setEnabled(true);*/
			btnNew.setVisibility(View.GONE);
			btnSavePrint.setVisibility(View.VISIBLE);
			btnSave.setVisibility(View.VISIBLE);
			btnCancelV.setVisibility(View.VISIBLE);
			
			txtMoney.setEnabled(true);
			txtCk.setEnabled(true);
			txtTotal.setEnabled(true);
			
			/*lnlFooter.setVisibility(View.GONE);*/
			break;
		case ACTION_VIEW:
			imgKhach_hang.setEnabled(false);
			txtNgay_ct.setEnabled(false);
			txtEmployee.setEnabled(false);
			txtStock.setEnabled(false);
			txtNote.setEnabled(false);
			/*txtBarcode.setEnabled(false);
			btnScan.setEnabled(false);
			btnEnter.setEnabled(false);*/
			txtMoney.setEnabled(false);
			txtCk.setEnabled(false);
			txtTotal.setEnabled(false);
			btnNew.setVisibility(View.VISIBLE);
			btnSavePrint.setVisibility(View.GONE);
			btnSave.setVisibility(View.GONE);
			btnCancelV.setVisibility(View.GONE);
			break;
		default:
			txtNgay_ct.setEnabled(false);
			imgKhach_hang.setEnabled(false);
			txtEmployee.setEnabled(false);
			txtStock.setEnabled(false);
			txtNote.setEnabled(false);
			/*txtBarcode.setEnabled(false);
			btnScan.setEnabled(false);
			btnEnter.setEnabled(false);*/
			
			txtMoney.setEnabled(true);
			txtCk.setEnabled(true);
			txtTotal.setEnabled(true);
			
			btnNew.setVisibility(View.VISIBLE);
			/*
			 * btnPrint.setVisibility(View.GONE);
			 * btnDelete.setVisibility(View.GONE);
			 * btnSearch.setVisibility(View.GONE);
			 */
			btnSavePrint.setVisibility(View.GONE);
			btnSave.setVisibility(View.GONE);
			btnCancelV.setVisibility(View.GONE);
			break;
		}
	}

	private void setValue() {
		switch (CURRENT_ACTION) {
		case ACTION_NEW:
			imgKhach_hang.setImageResource(R.drawable.partnera);
			Employee e = new Employee();
			e.setEmployeeID(Preferences.getPreferenceValue(getBaseContext(),
					Preferences.EMPLOYEEID));
			e.setEmployeeName(Preferences.getPreferenceValue(getBaseContext(),
					Preferences.EMPLOYEENAME));
			Partner p = new Partner();
			p.setPartnerID(Preferences.getPreferenceValue(getBaseContext(),
					Preferences.PARTNERID));
			p.setPartnerName(Preferences.getPreferenceValue(getBaseContext(),
					Preferences.PARTNERNAME));
			Stock s = new Stock();
			s.setStockID(Preferences.getPreferenceValue(getBaseContext(),
					Preferences.STOCKID));
			s.setStockName(Preferences.getPreferenceValue(getBaseContext(),
					Preferences.STOCKNAME));
			txtEmployee.setText(e.getEmployeeName());
			txtEmployee.setTag(e);

			txtStock.setText(s.getStockName());
			txtStock.setTag(s);
			tvPartnerName.setText(p.getPartnerName());
			imgKhach_hang.setTag(p);
			txtNote.setText("");
			txtBarcode.setText("");
			txtMoney.setText("");
			txtSo_ct.setText("");
			txtMoney.setTag(null);
			txtCk.setText("");
			txtTotal.setText("");
			ngay_ct = Formats.CurrentDate();
			txtNgay_ct.setText(Formats.DateFormatDisplay(ngay_ct));

			arrVoucherDetail = new ArrayList<VoucherDetail>();
			arrItem = new ArrayList<Item>();
			master = new VoucherMaster();
			master.setFK_bpkdID(e.getEmployeeID());
			master.setFK_khoID(s.getStockID());
			master.setFK_doitacID(p.getPartnerID());
			if (adapter == null) {
				adapter = new VoucherAdapter(getBaseContext(), arrVoucherDetail);
				lstVoucher.setAdapter(adapter);
			} else {
				adapter.swapData(arrVoucherDetail);
			}
			break;
		case ACTION_VIEW:

			break;
		case ACTION_START:
			txtEmployee.setText("");
			txtEmployee.setTag(null);
			txtStock.setText("");
			txtStock.setTag(null);
			tvPartnerName.setText("");
			imgKhach_hang.setTag(null);
			imgKhach_hang.setImageResource(R.drawable.partnera);
			txtNote.setText("");
			txtBarcode.setText("");
			txtMoney.setText("");
			txtCk.setText("");
			txtTotal.setText("");
			txtSo_ct.setText("");
			txtNgay_ct.setText("");
			arrVoucherDetail = new ArrayList<VoucherDetail>();
			arrItem = new ArrayList<Item>();
			master = new VoucherMaster();
			if (adapter == null) {
				adapter = new VoucherAdapter(getBaseContext(), arrVoucherDetail);
				lstVoucher.setAdapter(adapter);
			} else {
				adapter.swapData(arrVoucherDetail);
			}
			break;
		}
	}

	private class ItemAsync extends AsyncTask<Void, Void, Item> {
		ProgressDialog dialog;
		Item item;
		String key;
		String muaban;

		public ItemAsync(String key, String muaban) {
			// TODO Auto-generated constructor stub
			this.key = key;
			this.muaban = muaban;
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			dialog = new ProgressDialog(VoucherActivity.this);
			dialog.setMessage(getResources().getString(R.string.alert_waiting));
			dialog.show();
		}

		@Override
		protected void onPostExecute(Item result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			dialog.dismiss();
			item = result;
			if (item == null) {
				return;
			}
			ItemActivity.onStartIntent(VoucherActivity.this, item, Double.valueOf(1), item.getGia_ban11(), muaban, ACTION_NEW_ITEM, 0);
		}

		@Override
		protected Item doInBackground(Void... arg0) {
			// TODO Auto-generated method stub

			return WebService.getItemByID(getBaseContext(), key, muaban);
		}

	}

	private class VoucherAsync extends AsyncTask<String, Void, VoucherMaster> {
		ProgressDialog dialog;
		Boolean print = true;
		int step;

		public VoucherAsync(Boolean p, int s) {
			// TODO Auto-generated constructor stub
			print = p;
			this.step = s;
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			dialog = new ProgressDialog(VoucherActivity.this);
			dialog.setMessage(getResources().getString(R.string.alert_waiting));
			dialog.show();
		}

		@Override
		protected void onPostExecute(VoucherMaster result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (result == null) {
				Toast.makeText(getBaseContext(),
						R.string.alert_add_voucher_fail, Toast.LENGTH_LONG)
						.show();
			} else {
				master.setStt_rec(result.getStt_rec());
				master.setSo_ct(result.getSo_ct());
				txtSo_ct.setText(master.getSo_ct());
				Toast.makeText(getBaseContext(),
						R.string.alert_add_voucher_success, Toast.LENGTH_LONG)
						.show();
				CURRENT_ACTION = ACTION_VIEW;
				setAction();
				if (print) {
					startPrint(master.getStt_rec());
				}
			}
			dialog.dismiss();
		}

		@Override
		protected VoucherMaster doInBackground(String... arg0) {
			// TODO Auto-generated method stub
			return WebService.saveVoucher(getBaseContext(), master,
					arrVoucherDetail, step);
		}

	}

	private class DeleteVoucherAsync extends AsyncTask<String, Void, Boolean> {
		ProgressDialog dialog;

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			dialog = new ProgressDialog(VoucherActivity.this);
			dialog.setMessage(getResources().getString(R.string.alert_waiting));
			dialog.show();
		}

		@Override
		protected void onPostExecute(Boolean result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (result) {
				Toast.makeText(getBaseContext(),
						R.string.alert_delete_voucher_success,
						Toast.LENGTH_LONG).show();
				CURRENT_ACTION = ACTION_START;
				setValue();
				setAction();
			} else {
				Toast.makeText(getBaseContext(),
						R.string.alert_delete_voucher_fail, Toast.LENGTH_LONG)
						.show();
			}
			dialog.dismiss();
		}

		@Override
		protected Boolean doInBackground(String... arg0) {
			// TODO Auto-generated method stub
			return WebService.deleteVoucher(getBaseContext(), arg0[0], arg0[1]);
		}

	}

	private class PrintVoucherAsync extends AsyncTask<String, Void, Boolean> {
		int printtype = -1;

		public PrintVoucherAsync(int type) {
			// TODO Auto-generated constructor stubt
			printtype = type;
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			Toast.makeText(getBaseContext(), R.string.alert_printing,
					Toast.LENGTH_LONG).show();
		}

		@Override
		protected void onPostExecute(Boolean result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (result) {
				Toast.makeText(getBaseContext(),
						R.string.alert_print_voucher_success, Toast.LENGTH_LONG)
						.show();
			} else {
				Toast.makeText(getBaseContext(),
						R.string.alert_print_voucher_fail, Toast.LENGTH_LONG)
						.show();
			}
		}

		@Override
		protected Boolean doInBackground(String... arg0) {
			// TODO Auto-generated method stub
			return this.printtype != -1 ? WebService.printVoucher(
					getBaseContext(), arg0[0], printtype) : false;
		}

	}

	private void callist() {
		double tong_sl = 0;
		double tong_tien = 0;
		double ck = 0;
		double thanh_tien = 0;
		for (VoucherDetail v : arrVoucherDetail) {
			tong_tien = (v.getCtID1().equals("MUAHANG") ? -(v.getTien()) : v
					.getTien()) + tong_tien;
			tong_sl = (v.getCtID1().equals("MUAHANG") ? -(v.getSo_luong()) : v
					.getSo_luong()) + tong_sl;
		}
		ck = txtCk.getText().toString().trim().length() == 0 ? 0 : Double
				.valueOf(txtCk.getText().toString().replace(",", ""));
		thanh_tien = tong_tien - ck;
		txtMoney.setText(Formats.money(tong_tien));
		txtMoney.setTag(tong_sl == 0 ? null : tong_sl);
		txtTotal.setText(Formats.money(thanh_tien));
	}

	private void addItem(Item i, String ctid, Double soluong, Double thanhtien) {
		arrItem.add(i);
		VoucherDetail vd = new VoucherDetail();
		vd.setFK_VtID(i.getVtID());
		vd.setVtName(i.getVtName());
		vd.setFK_DvtID(i.getFK_DvtID());
		vd.setCtID1(ctid);
		vd.setTlg_au(i.getTlg_au());
		vd.setTlg_da(i.getTlg_da());
		vd.setHlg_au(i.getHlg_au());
		vd.setTong_tlg(i.getTong_tlg());
		vd.setTien_cong(i.getTien_cong());
		vd.setTien_da(i.getTien_da());
		vd.setGia(i.getGia_ban11());
		vd.setGia_au(i.getGia_au());
		vd.setTien(Double.valueOf(Math.round(thanhtien / 1000) * 1000));
		vd.setSo_luong(soluong);
		vd.setFK_TkID_dt(i.getFK_TkID_dt());
		vd.setFK_TkID_gv(i.getFK_TkID_gv());
		vd.setFK_TkID_vt(i.getFK_TkID_vt());
		arrVoucherDetail.add(vd);
		adapter.swapData(arrVoucherDetail);
		callist();
	}

	private void editItem(Item i, String ctid, Double soluong,
			Double thanhtien, int position) {
		arrItem.get(position).setTlg_au(i.getTlg_au());
		arrItem.get(position).setTlg_da(i.getTlg_da());
		arrItem.get(position).setTong_tlg(i.getTong_tlg());
		arrItem.get(position).setHlg_au(i.getHlg_au());
		arrItem.get(position).setTien_cong(i.getTien_cong());
		arrItem.get(position).setTien_da(i.getTien_da());
		arrItem.get(position).setGia_au(i.getGia_au());
		arrItem.get(position).setGia_ban11(i.getGia_ban11());

		arrVoucherDetail.get(position).setFK_VtID(i.getVtID());
		arrVoucherDetail.get(position).setVtName(i.getVtName());
		arrVoucherDetail.get(position).setFK_DvtID(i.getFK_DvtID());
		arrVoucherDetail.get(position).setCtID1(ctid);
		arrVoucherDetail.get(position).setTlg_au(i.getTlg_au());
		arrVoucherDetail.get(position).setTlg_da(i.getTlg_da());
		arrVoucherDetail.get(position).setHlg_au(i.getHlg_au());
		arrVoucherDetail.get(position).setTong_tlg(i.getTong_tlg());
		arrVoucherDetail.get(position).setTien_cong(i.getTien_cong());
		arrVoucherDetail.get(position).setTien_da(i.getTien_da());
		arrVoucherDetail.get(position).setGia(i.getGia_ban11());
		arrVoucherDetail.get(position).setGia_au(i.getGia_au());
		arrVoucherDetail.get(position).setTien(
				Double.valueOf(Math.round(thanhtien / 1000) * 1000));
		arrVoucherDetail.get(position).setSo_luong(soluong);
		adapter.swapData(arrVoucherDetail);
		callist();
	}

	private boolean checkChangeItem(Item i) {
		double tlg_au = Double.parseDouble(txtTlg_au.getText().toString()
				.replace(",", ""));
		if (tlg_au != i.getTlg_au().doubleValue()) {
			return true;
		}
		double tlg_da = Double.parseDouble(txtTlg_da.getText().toString()
				.replace(",", ""));
		if (tlg_da != i.getTlg_da().doubleValue()) {
			return true;
		}
		double tong_tlg = Double.parseDouble(txtTong_tlg.getText().toString()
				.replace(",", ""));
		if (tong_tlg != i.getTong_tlg().doubleValue()) {
			return true;
		}
		double tien_cong = Double.parseDouble(txtTien_cong.getText().toString()
				.replace(",", ""));
		if (tien_cong != i.getTien_cong().doubleValue()) {
			return true;
		}
		double tien_da = Double.parseDouble(txtTien_da.getText().toString()
				.replace(",", ""));
		if (tien_da != i.getTien_da().doubleValue()) {
			return true;
		}
		double gia_au = Double.parseDouble(txtGia_au.getText().toString()
				.replace(",", ""));
		if (gia_au != i.getGia_au().doubleValue()) {
			return true;
		}
		double gia_ban = Double.parseDouble(txtGia_ban11.getText().toString()
				.replace(",", ""));
		if (gia_ban != i.getGia_ban11().doubleValue()) {
			return true;
		}
		double hlg_au = Double.parseDouble(txtHlg_au.getText().toString()
				.replace(",", ""));
		if (hlg_au != i.getHlg_au().doubleValue()) {
			return true;
		}
		return false;
	}

	public static void onStartIntent(Context c) {
		Intent i = new Intent(c, VoucherActivity.class);
		i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		c.startActivity(i);
	}

}
